<?php 
global $_GPC, $_W;
$cfg = $this->module['config'];
$userid=$_GPC['_userid'];
if(!$userid)message('请先登录', '', 'error');
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
$user=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_user') . " WHERE id =:a",array(":a"=>$userid));
if(!$user || !$user['status'])message('账号异常', '', 'error');
$shop=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_group') . " WHERE id =:a",array(":a"=>$user['pcate']));
$shopid=$shop['id'];

if ($operation == 'memberpay') {
	$id=intval($_GPC['memberid']);
	if(!$id)die(json_encode(array('success'=>false,'msg'=>"请输入会员卡号")));
	$item = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$id));
    if($cfg["isgeneralbalance"])$item = pdo_fetch("SELECT a.*,b.credit1,b.credit2 FROM ".tablename('j_hmoney_membercard') ." a left join ".tablename('mc_members')." b on a.uid=b.uid WHERE a.weid = '{$_W['uniacid']}' and a.id=:a ",array(":a"=>$id));
	if(!$item)die(json_encode(array('success'=>false,'msg'=>"请输入ID号")));
	if($item['status']!=1)die(json_encode(array('success'=>false,'msg'=>"该会员卡状态异常，无法进行处理")));
	$cash=intval(abs($_GPC['cash'])*100);
	if($cash==0)die(json_encode(array('success'=>false,'msg'=>"请输入金额")));
	$data=array(
		"weid"=>$_W['uniacid'],
		"groupid"=>$shopid,
		"userid"=>$userid,
		"cid"=>$id,
		"usetype"=>0,
		"paytype"=>$_GPC['paytype'],
		"startfee"=>$item['cash']+intval($item['credit2']*100),
		"cash"=>$cash,
		"gift"=>intval($_GPC['gift']*100),
		"out_trade_no"=>TIMESTAMP.mt_rand(100,999),
		"remark"=>$_GPC['remark'],
		"createtime"=>TIMESTAMP,
		"createdate"=>date("Y-m-d"),
		"status"=>0,
	);
	pdo_insert("j_hmoney_recharge",$data);
	$pid=pdo_insertid();
	$qrcode=$_GPC['qrcode'];
	switch($data['paytype']){
		case 2:
		case 3:
			$data['status']=1;
		break;
		case 0:
			if($cfg['isbank']){
				$bank_trade_no=TIMESTAMP.mt_rand(1000,9999);
				pdo_update("j_hmoney_recharge",array('bank_trade_no'=>$bank_trade_no),array("id"=>$pid));
				$result=Bankpay_micropay($cfg,$cash,$bank_trade_no,$data['out_trade_no'],$qrcode,$userid,$shopid);
                if(isset($result["success"]) && $result["success"]==false){
                    die(json_encode(array("success"=>false,"msg"=>$result['msg'])));
                }
				if($result['status'] || $result['result_code']){
					if($result['err_code']=='10003' || $result['err_code']=='USERPAYING'){
						die(json_encode(array("success"=>true,"paywait"=>true,"pid"=>$pid)));
					}
					die(json_encode(array("success"=>false,"msg"=>$result['message'].$result['err_msg'])));
				}
				$data["status"]=1;
			}else{
				if(!$qrcode)die(json_encode(array('success'=>false,'msg'=>"请输入支付码")));
				$payParama=array(
					"appid"=>$shop['appid'] ? $shop['appid'] : $cfg['appid'],
					"pay_mchid"=>strval($shop['pay_mchid']) ? strval($shop['pay_mchid']) : strval($cfg['pay_mchid']),
					"pay_signkey"=>$shop['pay_signkey'] ? $shop['pay_signkey'] : $cfg['pay_signkey'],
					"outTradeNo"=>strval($data['out_trade_no']),
					"pay_ip"=>$shop['pay_ip'] ? $shop['pay_ip'] : $cfg['pay_ip'],
					"sub_appid"=>$shop['sub_appid'] ? $shop['sub_appid'] : $cfg['sub_appid'],
					"sub_mch_id"=>$shop['sub_mch_id'] ? $shop['sub_mch_id'] : $cfg['sub_mch_id'],
				);
				$pay_signkey=trim($shop['pay_signkey']) ? trim($shop['pay_signkey']) : trim($cfg['pay_signkey']);
				$pageparama=array(
					"appid"=>$shop['appid'] ? $shop['appid'] : $cfg['appid'],
					"mch_id"=>strval($shop['pay_mchid']) ? strval($shop['pay_mchid']) : strval($cfg['pay_mchid']),
					"device_info"=>$deviceinfo,
					"nonce_str"=>getNonceStr(),
					"body"=>$shop['companyname'],
					"detail"=>"充值",
					"attach"=>"-",
					"out_trade_no"=>$payParama['outTradeNo'],
					"total_fee"=>$data['cash'],
					"fee_type"=>"CNY",
					"spbill_create_ip"=>$shop['pay_ip'] ? $shop['pay_ip'] : $cfg['pay_ip'],
					"goods_tag"=>"000001",
					"auth_code"=>$qrcode,
				);
				if($payParama['sub_appid'])$pageparama['sub_appid']=$payParama['sub_appid'];
				if($payParama['sub_mch_id'])$pageparama['sub_mch_id']=$payParama['sub_mch_id'];
				$sign=MakeSign($pageparama,$pay_signkey);
				$pageparama['sign']=$sign;
				$xml = ToXml($pageparama);
				$response =postXmlCurl($xml, "https://api.mch.weixin.qq.com/pay/micropay", 10);
				$result=FromXml($response);
				if($result['result_code']!='SUCCESS'){
					if($result['err_code']=='USERPAYING'){
						die(json_encode(array("success"=>true,"paywait"=>true,"out_trade_no"=>$payParama['outTradeNo'],"pid"=>$pid)));
					}
					die(json_encode(array("success"=>false,"msg"=>$result['err_code_des'])));
				}
				$data["status"]=1;
			}
			
		break;
		case 1:
			if($cfg['isbank']){
				$bank_trade_no=TIMESTAMP.mt_rand(1000,9999);
				pdo_update("j_hmoney_recharge",array('bank_trade_no'=>$bank_trade_no),array("id"=>$pid));
				$result=Bankpay_micropay($cfg,$cash,$bank_trade_no,$data['out_trade_no'],$qrcode,$userid,$shopid);
                if(isset($result["success"]) && $result["success"]==false){
                    die(json_encode(array("success"=>false,"msg"=>$result['msg'])));
                }
				if($result['status'] || $result['result_code']){
					if($result['err_code']=='10003' || $result['err_code']=='USERPAYING'){
						die(json_encode(array("success"=>true,"paywait"=>true,"pid"=>$pid)));
					}
					die(json_encode(array("success"=>false,"msg"=>$result['message'].$result['err_msg'])));
				}
				$data["status"]=1;
			}else{
				$qrcode=$_GPC['qrcode'];
				$payParama=array(
					"app_id"=>$shop['app_id'] ? $shop['app_id'] : $cfg['app_id'],
					"outTradeNo"=>strval($data['out_trade_no']),
					"appauthtoken"=>$shop['appauthtoken'] ? $shop['appauthtoken'] : $cfg['appauthtoken'],
					"alipay_cert"=>$cfg['alipay_cert'],
					"alipay_key"=>$cfg['alipay_key'],
					"alipay_store_id"=>$shop['alipay_store_id'] ,
					"alipid"=>$cfg['alipid'] ,
				);
				$auth_code = trim($qrcode);
				$total_amount = $data['cash'];
				$postfee=$this->_2money(($total_amount));
				require_once '../addons/j_hmoney/plug/plug_alipay/F2fpay.php';
				$f2fpay = new F2fpay();
				$response = $f2fpay->barpay($payParama['outTradeNo'],$auth_code,$postfee,$shop['companyname'],$payParama);
				$temp=(array)$response;
				$result=(array)$temp['alipay_trade_pay_response'];
				if($result['code']=="10003"){
					die(json_encode(array("success"=>true,"paywait"=>true,"out_trade_no"=>$payParama['outTradeNo'],"pid"=>$pid)));
				}elseif($result['code']=="10000"){
					$data["status"]=1;
				}else{
					die(json_encode(array("success"=>false,"msg"=>$result['sub_msg'])));
				}
			}
		
		break;
	}
	$data['endfee']=($item['cash']+intval($item['credit2']*100))+abs($cash)+$data['gift'];
	pdo_update("j_hmoney_recharge",$data,array("id"=>$pid));
	pdo_update("j_hmoney_membercard",array("cash"=>$item['cash']+abs($cash)+$data['gift']),array("id"=>$id));
	if($item['uid'])$this->memberCardInform($id);
    /*发送通知*/
    $item = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$id));
    if($cfg["isgeneralbalance"])$item = pdo_fetch("SELECT a.*,b.credit1,b.credit2 FROM ".tablename('j_hmoney_membercard') ." a left join ".tablename('mc_members')." b on a.uid=b.uid WHERE a.weid = '{$_W['uniacid']}' and a.id=:a ",array(":a"=>$id));
    $temstr=urldecode($cfg['tempmsg_payparama']);
    $tempstr=str_replace("|单号|",$data['out_trade_no'],$temstr);
    $tempstr=str_replace("|店铺|",$shop['companyname'],$tempstr);
    $tempstr=str_replace("|时间|",date("m/d H:i",$data['createtime']),$tempstr);
    $tempstr=str_replace("|处理人|",$user['realname'],$tempstr);
    $tempstr=str_replace("|总金额|","￥".$this->_2money(($cash)),$tempstr);
    $tempstr=str_replace("|优惠|","",$tempstr);
    $tempstr=str_replace("|实付金额|","￥".$this->_2money(($cash)),$tempstr);
    $paystr=_getPaytpye($data['paytype'],$shopid);
    $tempstr=str_replace("|支付方式|",$paystr,$tempstr);
    $itemary=json_decode($tempstr,true);
    $temp=array();
    foreach($itemary as $key=>$val){
        $temp[$key]=array(
            "value"=>$val['value'],
            "color"=>$val['color'] ? $val['color']: "#333333",
        );
    }
    $temp['remark']["value"]="充值卡号：".$item["cardno"];
    $acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
    $acc = WeAccount::create($acid);
    if($user['openid'])$acc->sendTplNotice($user['openid'],$cfg["tempmsg_pay"],$temp,"","#FF0000");
    $userlist=pdo_fetchall("SELECT openid FROM ".tablename('j_money_user')." WHERE  pcate=:a and permission>1 and openid",array(":a"=>$shopid));
    if($user["openid"])$data=$acc->sendTplNotice($user["openid"],$cfg["tempmsg_pay"],$temp,"","#FF0000");
    if(count($userlist)){
        foreach($userlist as $row){
            if($row["openid"]==$user['openid'])continue;
            $acc->sendTplNotice($row["openid"],$cfg["tempmsg_pay"],$temp,"","#FF0000");
        }
    }
	die(json_encode(array("success"=>true,"out_trade_no"=>$data['out_trade_no'],"pid"=>$pid,"id"=>$id)));
	
}elseif ($operation == 'reversepay') {
	$pid=$_GPC['pid'];
	$item = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_recharge') . " WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$pid));
	$payParama=array(
		"appid"=>$shop['appid'] ? $shop['appid'] : $cfg['appid'],
		"pay_mchid"=>strval($shop['pay_mchid']) ? strval($shop['pay_mchid']) : strval($cfg['pay_mchid']),
		"pay_signkey"=>$shop['pay_signkey'] ? $shop['pay_signkey'] : $cfg['pay_signkey'],
		"pay_ip"=>$shop['pay_ip'] ? $shop['pay_ip'] : $cfg['pay_ip'],
		"sub_appid"=>$shop['sub_appid'] ? $shop['sub_appid'] : $cfg['sub_appid'],
		"sub_mch_id"=>$shop['sub_mch_id'] ? strval($shop['sub_mch_id']) : strval($cfg['sub_mch_id']),
		"apiclient_cert"=>$shop['apiclient_cert'] ? '../attachment/j_hmoney/cert_2/'.$_W['uniacid']."/".$trade['groupid']."/".$shop['apiclient_cert'] : '../attachment/j_hmoney/cert_2/'.$_W['uniacid']."/".$cfg['apiclient_cert'],
		"apiclient_key"=>$shop['apiclient_key'] ? '../attachment/j_hmoney/cert_2/'.$_W['uniacid']."/".$trade['groupid']."/".$shop['apiclient_key'] : '../attachment/j_hmoney/cert_2/'.$_W['uniacid']."/".$cfg['apiclient_key'],
	);
	$pageparama=array(
		"appid"=>$payParama['appid'],
		"mch_id"=>$payParama['pay_mchid'],
		"nonce_str"=>getNonceStr(),
		"out_trade_no"=>$item['out_trade_no'],
	);
	if($payParama['sub_appid'])$pageparama['sub_appid']=$payParama['sub_appid'];
	if($payParama['sub_mch_id'])$pageparama['sub_mch_id']=$payParama['sub_mch_id'];
	$sign=MakeSign($pageparama,$payParama['pay_signkey']);
	$pageparama['sign']=$sign;
	$xml = ToXml($pageparama);
	$pemary=array("cert"=>$payParama['apiclient_cert'],"key"=>$payParama['apiclient_key'],);
	$response =postXmlAndPemCurl($xml, "https://api.mch.weixin.qq.com/secapi/pay/reverse", $pemary);
	$result=FromXml($response);
	if($result['return_code']=='SUCCESS' && $result['result_code']=='SUCCESS'){
		pdo_delete("j_hmoney_recharge",array("id"=>$pid));
		die(json_encode(array("success"=>true)));
	}
	die(json_encode(array("success"=>false,"msg"=>$result['return_msg'].$result['err_code_des'])));
	
}elseif ($operation == 'waitforpass') {
	$pid=$_GPC['pid'];
	$trade = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_recharge') . " WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$pid));
	$item = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' $condition and id=:a ",array(":a"=>$trade['cid']));
	if($cfg['isbank']){
		$result=Bankpay_checkpay($cfg,$trade['bank_trade_no']);
		if(!$result['status'] && !$result['result_code']){
			if($result['trade_state']=='USERPAYING' || $result['trade_state']=='10003'){
				die(json_encode(array("success"=>true,"paywait"=>true,"orderid"=>$orderid)));
			}elseif($result['trade_state']=='SUCCESS'){
				$data=array("status"=>1,'endfee'=>$item['cash']+$trade['cash']+$trade['gift']);
				pdo_update("j_hmoney_recharge",$data,array("id"=>$pid));
				pdo_update("j_hmoney_membercard",array("cash"=>$item['cash']+$trade['cash']+$trade['gift']),array("id"=>$item['id']));
				$this->memberCardInform($item['id']);
				die(json_encode(array("success"=>true,"paywait"=>false,"pid"=>$pid,"id"=>$item['id'])));
			}
			die(json_encode(array("success"=>false,"msg"=>$result['trade_state'])));
		}
		die(json_encode(array("success"=>false,"msg"=>$result['message'].$result['err_msg'])));
		
	}else{
		if($item['paytype']==0){
			$payParama=array(
				"appid"=>$shop['appid'] ? $shop['appid'] : $cfg['appid'],
                "sub_appid"=>$shop['sub_appid'] ? $shop['sub_appid'] : $cfg['sub_appid'],
                "sub_mch_id"=>$shop['sub_mch_id'] ? $shop['sub_mch_id'] : $cfg['sub_mch_id'],
				"pay_mchid"=>strval($shop['pay_mchid']) ? strval($shop['pay_mchid']) : strval($cfg['pay_mchid']),
				"pay_signkey"=>$shop['pay_signkey'] ? $shop['pay_signkey'] : $cfg['pay_signkey'],
			);
			$pageparama=array(
				"appid"=>$payParama['appid'],
				"mch_id"=>strval($payParama['pay_mchid']),
				"out_trade_no"=>$trade['out_trade_no'],
				"nonce_str"=>getNonceStr(),
			);
			if($payParama['sub_appid'])$pageparama['sub_appid']=$payParama['sub_appid'];
			if($payParama['sub_mch_id'])$pageparama['sub_mch_id']=$payParama['sub_mch_id'];
			$sign=MakeSign($pageparama,$payParama['pay_signkey']);
			$pageparama['sign']=$sign;
			$xml = ToXml($pageparama);
			$response =postXmlCurl($xml, "https://api.mch.weixin.qq.com/pay/orderquery", 10);
			$result=FromXml($response);
			if($result['result_code']=='SUCCESS'){
				if($result['trade_state']=='USERPAYING'){
					die(json_encode(array("success"=>true,"paywait"=>true,"pid"=>$pid)));
				}elseif($result['trade_state']=='SUCCESS'){
					if($trade['status']>0){
						die(json_encode(array("success"=>true,"paywait"=>false,"pid"=>$pid,"id"=>$item['id'])));
					}
					$data=array("status"=>1,'endfee'=>$item['cash']+$trade['cash']+$trade['gift']);
					pdo_update("j_hmoney_recharge",$data,array("id"=>$pid));
					pdo_update("j_hmoney_membercard",array("cash"=>$item['cash']+$trade['cash']+$trade['gift']),array("id"=>$item['id']));
					$this->memberCardInform($item['id']);
					die(json_encode(array("success"=>true,"paywait"=>false,"pid"=>$pid,"id"=>$item['id'])));
				}
			}
			die(json_encode(array("success"=>false,"msg"=>$result['trade_state_desc'].$result['err_code_des'])));
			
		}else if($item['paytype']==1){
			$payParama=array(
				"app_id"=>$shop['app_id'] ? $shop['app_id'] : $cfg['app_id'],
				"pemurl"=>$cfg['pemurl'],
				"appauthtoken"=>$shop['appauthtoken'] ? $shop['appauthtoken'] : $cfg['appauthtoken'],
				"alipay_cert"=>$cfg['alipay_cert'],
				"alipay_key"=>$cfg['alipay_key'],
				"alipay_store_id"=>$shop['alipay_store_id'] ,
				"alipid"=>$cfg['alipid'] ,
			);
			if($payParama['app_id']==$payParama['sub_app_id'])unset($payParama['sub_app_id']);
			require_once '../addons/j_hmoney/plug/plug_alipay/F2fpay.php';
			$cfg = $this->module['config'];
			$f2fpay = new F2fpay();
			$response = $f2fpay->query($trade['out_trade_no'],$payParama);
			$results=@json_decode(json_encode($response),true);
			$result=$results['alipay_trade_query_response'];
			if($result['code']==10003){
				die(json_encode(array("success"=>true,"paywait"=>true,"pid"=>$pid,"id"=>$item['id'])));
			}elseif($result['code']==10000){
				if($result['trade_status']=="TRADE_SUCCESS"){
					if($trade['status']>0){
						die(json_encode(array("success"=>true,"paywait"=>false,"pid"=>$pid,"id"=>$item['id'])));
					}
					$data=array("status"=>1,'endfee'=>$item['cash']+$trade['cash']+$trade['gift']);
					pdo_update("j_hmoney_recharge",$data,array("id"=>$pid));
					pdo_update("j_hmoney_membercard",array("cash"=>$item['cash']+$trade['cash']+$trade['gift']),array("id"=>$item['id']));
					$this->memberCardInform($item['id']);
					die(json_encode(array("success"=>true,"paywait"=>false,"pid"=>$pid,"id"=>$item['id'])));
				}
			}
			die(json_encode(array("success"=>false,"msg"=>$result['sub_msg'])));
		}
		die(json_encode(array('success'=>true)));
	}
	
	
}elseif ($operation == 'getallmember') {
	$total_birday=pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('j_hmoney_membercard') . " WHERE groupid ='".$shopid."' and  date_format(birdday,'%m-%d')='".date("m-d")."' ");
	$total_b=pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('j_hmoney_membercard') . " WHERE groupid ='".$shopid."' and  date_format(birdday,'%m')='".date("m")."' and date_format(birdday,'%d')>='".date("d")."' ");
	
	$total_all=pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' ");
	$total3=pdo_fetchcolumn('SELECT sum(cash) FROM ' . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' ");
	$total3_1=pdo_fetchcolumn('SELECT sum(credit2) FROM ' . tablename('mc_members') . " WHERE uid in(SELECT uid FROM ".tablename('j_hmoney_membercard')." WHERE uid<>0 and weid = '{$_W['uniacid']}') ");
	$total_cash=$this->_2money((intval($total3+$total3_1*100)));
	$total4=pdo_fetch('SELECT sum(cash) as fee,count(*) as num FROM ' . tablename('j_hmoney_recharge') . " WHERE groupid ='".$shopid."' and usetype=1 and status=1 and date_format(createdate,'%y-%m')='".date('y-m')."'");
	$total5=pdo_fetchcolumn('SELECT sum(cash) FROM ' . tablename('j_hmoney_recharge') . " WHERE groupid ='".$shopid."' and usetype=1 and status=1  ");
	$total_charge=pdo_fetchcolumn('SELECT sum(cash) FROM ' . tablename('j_hmoney_recharge') . " WHERE groupid ='".$shopid."' and date_format(createdate,'%y-%m')='".date('y-m')."' and usetype=0 and status=1 ");
	$data=array(
		'success'=>true,
		'num1'=>$total_birday,
		'num2'=>$total_b,
		'num3'=>$total_all,
		'num4'=>$total_cash,
		'num5'=>$this->_2money((abs($total4['fee']))),
		'num6'=>$total4['num'],
		'num7'=>$this->_2money(($total_charge)),
	);
	die(json_encode($data));
	
}elseif ($operation == 'getmemberpage') {
	$pindex = max(1, intval($_GPC['page']));
	$psize = 5;
	$condition = "  ";
	if($_GPC['keyword'])$condition.= " and ( cardno='".$_GPC['keyword'] ."' or wxcardno='".$_GPC['keyword'] ."' or mobile = '".$_GPC['keyword']."')";
	$list = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' $condition order by id desc  LIMIT ".($pindex - 1) * $psize . ',' . $psize);
	$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('j_hmoney_membercard') . " WHERE weid='{$_W['uniacid']}' $condition");
	if($cfg['isgeneralbalance']){
        if($_GPC['keyword'])$condition1= " and ( a.cardno='".$_GPC['keyword'] ."' or a.wxcardno='".$_GPC['keyword'] ."' or a.mobile = '".$_GPC['keyword']."')";
		$list = pdo_fetchall("SELECT a.*,b.credit1,b.credit2 FROM ".tablename('j_hmoney_membercard') ." a left join ".tablename('mc_members')." b on a.uid=b.uid WHERE a.weid = '{$_W['uniacid']}' $condition1 order by a.id desc  LIMIT " . ($pindex - 1) * $psize . ',' . $psize);
	}
    $groupAry=array();
    $groupAry[0]="";
    foreach(mc_groups() as $row){
        $groupAry[$row['groupid']]=$row['title'];
    }
	for($i=0;$i<count($list);$i++){
        $list[$i]['level']=$groupAry[$list[$i]['gid']];
		$temp1=$this->_2money((($list[$i]['credit']*100+$list[$i]['credit1']*100)));
		$list[$i]['credit']=$temp1;
		$temp2=$this->_2money((($list[$i]['cash']+$list[$i]['credit2']*100)));
		$list[$i]['cash']=$temp2;
	}
	die(json_encode(array('success'=>true,'list'=>$list,'pindex'=>$pindex,'total'=>$total)));
	
}elseif ($operation == 'getmember') {
	$id=$_GPC['id'];
	$keyword=trim($_GPC['keyword']);
	$condition = " and groupid ='".$shopid."' ";
	if($keyword){
		$condition.= "  and (realname =:a or cardno =:a or wxcardno=:a or mobile=:a) ";
		$list = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' $condition ",array(":a"=>$keyword));
		die(json_encode(array('success'=>true,'list'=>$list)));
	}
	if(!$id)die(json_encode(array('success'=>false,'msg'=>"请输入ID号")));
	$condition = "  ";
	$member = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' $condition and id=:a ",array(":a"=>$id));
	$member['cash2']=$member['cash'];
	$member['bird']=$member['birdday'] ? date("m/d",$member['birdday']) : "-";
	$groupAry=array();
	foreach(mc_groups() as $row){
		$groupAry[$row['groupid']]=$row['title'];
	}
	$member['credit2']=$member['credit'];
	$member['level']=$groupAry[$member['gid']];
	if($member['uid'] || $member['openid'] ){
		$uid=$member['uid'];
		if(!$uid)$uid=mc_openid2uid($member['openid']);
		$memberuser=mc_fetch($uid);
		if($cfg['isgeneralbalance'])$member['cash2']=$member['cash2']+intval($memberuser['credit2']*100);
		$member['credit2']=$member['credit']+$memberuser['credit1'];
	}
	$member['cash2']=$this->_2money(($member['cash2']));	
	die(json_encode(array('success'=>true,'item'=>$member)));
	
}elseif ($operation == 'postmember') {
	$id=intval($_GPC['modal_memberEdit_id']);
	$data=array(
		"weid"=>$_W["uniacid"],
		"groupid"=>$shopid,
		"cardno"=>$_GPC["mmEdit_cardno"],
		"userid"=>$userid,
        "createtime"=>TIMESTAMP,
		"gid"=>$_GPC["mmEdit_gid"],
		"realname"=>$_GPC["mmEdit_realname"],
		"sex"=>$_GPC["mmEdit_sex"],
		"mobile"=>$_GPC["mmEdit_mobile"],
		"wxcardno"=>$_GPC["mmEdit_wxcardno"],
		"remark"=>$_GPC["mmEdit_remark"],
		"endtime"=>$_GPC["mmEdit_endtime"],
		"status"=>$_GPC["mmEdit_status"],
		"birdday"=>$_GPC["mmEdit_birdday"],
		"label"=>$_GPC["mmEdit_label"],
	);
	$update=array(
		"cardno"=>$data["cardno"],
		"wxcardno"=>$data["wxcardno"],
	);
	if($id){

		unset($data['userid']);
		unset($data['groupid']);
        unset($data['createtime']);
        $member=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_membercard')." WHERE id=:a ",array(":a"=>$id));
		$isused=pdo_fetchcolumn("SELECT count(*) FROM " . tablename('j_hmoney_membercard') . " WHERE weid=:c and cardno=:b and id<>:a ",array(":a"=>$id,":b"=>$data['cardno'],":c"=>$_W['uniacid']));
		if($isused)die(json_encode(array('success'=>false,'msg'=>"实体卡号/微信卡号重复")));
		if($_GPC["mmEdit_wxcardno"]){
			$isused=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('j_hmoney_membercard')." WHERE weid=:c and wxcardno=:b and id<>:a ",array(":a"=>$id,":c"=>$_W['uniacid'],":b"=>$data['wxcardno']));
			if($isused)die(json_encode(array('success'=>false,'msg'=>"实体卡号/微信卡号重复")));
		}else{
            $data["uid"]="0";
            $data["openid"]="";
        }
        if($member["cardno"])unset($data['cardno']);
		pdo_update("j_hmoney_membercard",$data,array("id"=>$id));
        $member=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_membercard')." WHERE id=:a ",array(":a"=>$id));
		$update['uid']=$member['uid'];
		$update['openid']=$member['openid'];
	}else{
		$isused=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('j_hmoney_membercard')." WHERE weid=:c and cardno=:b ",array(":b"=>$data['cardno'],":c"=>$_W['uniacid']));
		if($isused)die(json_encode(array('success'=>false,'msg'=>"实体卡号/微信卡号重复")));
		if($_GPC["mmEdit_wxcardno"]){
			$isused=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('j_hmoney_membercard')." WHERE weid=:c and wxcardno=:b ",array(":c"=>$_W['uniacid'],":b"=>$data['wxcardno']));
			if($isused)die(json_encode(array('success'=>false,'msg'=>"实体卡号/微信卡号重复")));
		}
		pdo_insert("j_hmoney_membercard",$data);
		$id=pdo_insertid();
	}
	if($update['wxcardno'] && $cfg['wxmembercard'] && (!$update['openid'] || !$update['uid'])){
		//通过卡号获取openid
		$acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
		$acc = WeAccount::create($acid);
		$tokens=$acc->fetch_token();
		$pageparama=json_encode(array("card_id"=>$cfg['wxmembercard'],"code"=>$update['wxcardno']));
		$resp = ihttp_request("https://api.weixin.qq.com/card/membercard/userinfo/get?access_token=".$tokens,$pageparama, $xml);
		$result=@json_decode($resp['content'],true);
		if(!$result['errcode']){
			$openid=$result['openid'];
			$uid=mc_openid2uid($openid);
			pdo_update("j_hmoney_membercard",array("openid"=>$openid,"uid"=>$uid),array("id"=>$id));
			$this->memberCardInform($id);
		}
	}
	die(json_encode(array('success'=>true)));
}elseif ($operation == 'searchwxmember') {
    $wxcard=$_GPC["wxcard"];
    if(!$wxcard)die(json_encode(array('success'=>false,'msg'=>"卡号不能为空")));
    $acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
    $acc = WeAccount::create($acid);
    $tokens=$acc->fetch_token();
    $pageparama=json_encode(array("card_id"=>$cfg['wxmembercard'],"code"=>$wxcard));
    $resp = ihttp_request("https://api.weixin.qq.com/card/membercard/userinfo/get?access_token=".$tokens,$pageparama, $xml);
    $result=@json_decode($resp['content'],true);
    if(!$result['errcode']){
        //var_dump($result['user_info']);
        $info=$result['user_info']['common_field_list'];
        $data=array();
        foreach($info as $index=>$row){
            if($row['name']=='USER_FORM_INFO_FLAG_MOBILE'){
                $data['手机']=$row['value'];
            }elseif($row['name']=='USER_FORM_INFO_FLAG_NAME'){
                $data['姓名']=$row['value'];
            }elseif($row['name']=='USER_FORM_INFO_FLAG_SEX'){
                $data['性别']=$row['value'];
            }elseif($row['name']=='USER_FORM_INFO_FLAG_BIRTHDAY'){
                $data['生日']=$row['value'];
            }else{
                $data[$row['name']]=$row['value'];
            }
        }
        $info2=$result['user_info']['custom_field_list'];
        foreach($info2 as $index=>$row){
            $data[$row['name']]=$row['value'];
        }
        die(json_encode(array('success'=>true,'cardinfo'=>$data)));
    }
    die(json_encode(array('success'=>false,'msg'=>"无此会员")));


}elseif ($operation == 'reviewmember') {
    $id=intval($_GPC["id"]);
    $member = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$id));
    load()->func('communication');
    $cfg = $this->module['config'];
    $cardid=$cfg["wxmembercard"];
    if(!$cardid)die(json_encode(array("success"=>false,"msg"=>"请先填写会员卡ID并保存后操作")));
    $acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
    $acc = WeAccount::create($acid);
    $tokens=$acc->fetch_token();
    $data2=array(
        "openid"=>$member["openid"],
        "card_id"=>$cardid
    );
    $pageparama=urldecode(json_encode($data2));
    $resp = ihttp_request("https://api.weixin.qq.com/card/user/getcardlist?access_token=".$tokens,$pageparama, "");
    $result=@json_decode($resp['content'],true);
    if($result['errcode'] || !isset($result['errcode']) || $result['errmsg']!="ok")die(json_encode(array("success"=>true,"msg"=>$result['errmsg'])));
    $code=$result["card_list"][0]["code"];
    if(!$code)die(json_encode(array("success"=>true,"msg"=>$result['没匹配会员卡'])));

    //die(json_encode(array("success"=>true,"code"=>$code)));

    $tokens=$acc->fetch_token();
    $data=array(
        "membership_number"=>$code,
        "code"=>$code,
        "card_id"=>$cardid
    );
    $pageparama=urldecode(json_encode($data));
    $resp = ihttp_request("https://api.weixin.qq.com/card/membercard/activate?access_token=".$tokens,$pageparama, "");
    $result=@json_decode($resp['content'],true);
    if($result['errcode'] || !isset($result['errcode']) || $result['errmsg']!="ok")die($result['errmsg']);
    /**/
    $update=array(
        "groupid"=>$member["groupid"] ? $member["groupid"] : $shopid,
        "userid"=>$member["userid"] ? $member["userid"] : $userid,
        "wxcardno"=>$code,
        "createtime"=>TIMESTAMP,
    );
    if(!$member["mobile"]){
        $tokens=$acc->fetch_token();
        $data=array(
            "code"=>$code,
            "card_id"=>$cardid
        );
        $pageparama=urldecode(json_encode($data));
        $resp = ihttp_request("https://api.weixin.qq.com/card/membercard/userinfo/get?access_token=".$tokens,$pageparama, "");
        $result=@json_decode($resp['content'],true);
        if($result['errcode'] || !isset($result['errcode']) || $result['errmsg']!="ok")die(json_encode(array("success"=>true,"msg"=>$result['errmsg'])));
        $info=$result['user_info']['common_field_list'];
        $data=array();
        foreach($info as $index=>$row){
            if($row['name']=='USER_FORM_INFO_FLAG_MOBILE'){
                $update['mobile']=$row['value'];
            }elseif($row['name']=='USER_FORM_INFO_FLAG_NAME'){
                $update['realname']=$row['value'];
            }elseif($row['name']=='USER_FORM_INFO_FLAG_SEX'){
                if($row["value"]=="男"){
                    $update["sex"]=1;
                }elseif($row["value"]=="女"){
                    $update["sex"]=2;
                }else{
                    $update["sex"]=0;
                }
            }elseif($update['name']=='USER_FORM_INFO_FLAG_BIRTHDAY'){
                $data['birdday']=$row['value'];
            }
        }
    }
    pdo_update("j_hmoney_membercard",$update,array("id"=>$member["id"]));
    die(json_encode(array("success"=>true,"code"=>$code)));
}












